package com.xywl.escort.view.user

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bilibili.boxing.Boxing
import com.bilibili.boxing.model.config.BoxingConfig
import com.bilibili.boxing.model.config.BoxingCropOption
import com.bilibili.boxing.model.entity.impl.ImageMedia
import com.bilibili.boxing.utils.BoxingFileHelper
import com.bilibili.boxing_impl.ui.BoxingActivity
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.bean.UserAutoInfoResp
import com.xywl.escort.bean.UserInfoResp
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys.*
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_user_info.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import top.zibin.luban.Luban
import java.io.File
import java.util.*
import javax.inject.Inject


@Route(path = "/xy/user/info")
class UserInfoActivity : BaseActivity(), UserInfoContract.View {
    private val REQUEST_CODE_CHOOSE = 23
    @Inject
    lateinit var mPresenter: UserInfoContract.Presenter

    private var mDisposable: CompositeDisposable? = null
    private var mDataBean: UserAutoInfoResp.DataBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)

        val cachePath = BoxingFileHelper.getCacheDir(this)
        initData()
        addListener(cachePath!!)

        mDisposable = CompositeDisposable()
        EventBus.getDefault().register(this)
    }

    private fun initData() {
        mPresenter.takeView(this)
        val userId = RxSPTool.getString(this, USER_ID)
        mPresenter.findUserInfo(userId)
    }

    override fun onResume() {
        super.onResume()
        val userId = RxSPTool.getString(this, USER_ID)
        mPresenter.findUserAutoInfo(userId)
    }

    private fun addListener(cachePath: String) {
        icon_avatar.setOnClickListener {
            // val cachePath = BoxingFileHelper.getCacheDir(this)
            requestPermissions(cachePath)
        }

        layout_phone.setOnClickListener {
            ARouter.getInstance().build("/xy/modify/phone").navigation()
        }

        layout_certified.setOnClickListener {
            ARouter.getInstance()
                    .build("/xy/certified")
                    .withObject("dataBean", mDataBean)
                    .navigation()
        }

        text_bank_card.setOnClickListener {
            ARouter.getInstance().build("/xy/band/card/list").navigation()
        }

        text_save.setOnClickListener {
            val userId = RxSPTool.getString(this, USER_ID)
            val nickname = edit_nickname.text.toString().trim()
            if (!TextUtils.isEmpty(nickname)) {
                mPresenter.updateUserInfo(nickname, userId)
            } else {
                ToastUtil.showTip(this, "昵称不能为空")
            }
        }
    }

    private fun requestPermissions(cachePath: String) {
        val rxPermission = RxPermissions(this)
        rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { permission ->
                    when {
                        permission.granted -> {
                            // 用户已经同意该权限
                            Timber.d(permission.name + " is granted.")
                            openBoxing(cachePath)
                        }
                        permission.shouldShowRequestPermissionRationale -> {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Timber.d(permission.name + " is denied. More info should be provided.")
                        }
                        else -> {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Timber.d(permission.name + " is denied.")
                        }
                    }
                }
    }

    private fun openBoxing(cachePath: String) {
        if (TextUtils.isEmpty(cachePath)) {
            Toast.makeText(applicationContext, R.string.boxing_storage_deny, Toast.LENGTH_SHORT).show()
        } else {
            val destUri = Uri.Builder()
                    .scheme("file")
                    .appendPath(cachePath)
                    .appendPath(String.format(Locale.US, "%s.png", "avatar"))
                    .build()
            val singleCropImgConfig = BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(BoxingCropOption(destUri))
                    .needCamera(R.mipmap.ic_photo_camera_white_24dp).needGif()
                    .withMediaPlaceHolderRes(R.mipmap.icon_default_picture)
            Boxing.of(singleCropImgConfig).withIntent(this, BoxingActivity::class.java).start(this, REQUEST_CODE_CHOOSE)
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun findUserInfoSuccess(dataBean: UserInfoResp.DataBean?) {
        var nickname = dataBean!!.nickname
        if (TextUtils.isEmpty(nickname)) {
            nickname = dataBean.account
        } else {
            RxSPTool.putString(this, NICK_NAME, nickname)
        }
        edit_nickname.setText(nickname)
        val path = dataBean.headImg
        if (!TextUtils.isEmpty(path)) {
            RxSPTool.putString(this, HEAD_IMG, path)
            GlideApp.with(this)
                    .load(path)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .placeholder(R.mipmap.icon_default_picture)
                    .into(icon_avatar)
        } else {
            GlideApp.with(this)
                    .load(R.mipmap.icon_default_picture)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .placeholder(R.mipmap.icon_default_picture)
                    .into(icon_avatar)
        }
        text_phone.text = dataBean.account
    }

    override fun findUserInfoFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun updateNicknameSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "修改个人信息成功")
        val nickname = edit_nickname.text.toString().trim()
        if (!TextUtils.isEmpty(nickname)) {
            RxSPTool.putString(this, NICK_NAME, nickname)
        }
        finish()
    }

    override fun updateAvatarSuccess(resp: BaseResp?, headImg: String) {
        ToastUtil.showTip(this, "修改个人信息成功")
        if (!TextUtils.isEmpty(headImg)) {
            RxSPTool.putString(this, HEAD_IMG, headImg)
        }
    }

    override fun updateUserInfoFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun findUserAutoInfoSuccess(dataBean: UserAutoInfoResp.DataBean?) {
        mDataBean = dataBean!!
        when (dataBean.status) {
        // 1未认证2审核中3已认证4未通过
            1 -> {
                text_certified.text = "未认证"
            }
            2 -> {
                text_certified.text = "审核中"
            }
            3 -> {
                text_certified.text = "已认证"
            }
            4 -> {
                text_certified.text = "未通过"
            }
            else -> {
                text_certified.text = "未认证"
            }
        }
    }

    override fun findUserAutoInfoFailure() {
        text_certified.text = "未认证"
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            data?.let {
                val medias = Boxing.getResult(data)

                medias?.let {
                    val baseMedia = medias[0] as? ImageMedia ?: return
                    val path = baseMedia.thumbnailPath
                    Timber.tag("UserInfoActivity").e("path=$path")

                    val files = ArrayList<File>()
                    val file = File(path)
                    files.add(file)
                    withRx(files)
                }
            }
        }
    }

    private fun <T> withRx(photos: List<T>) {
        val userId = RxSPTool.getString(this, USER_ID)
        val nickname = edit_nickname.text.toString()
        mDisposable!!.add(Flowable.just(photos)
                .observeOn(Schedulers.io())
                .map { list ->
                    Luban.with(this).load(list).get()
                }
                .compose(this.bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { list ->
                    for (file in list) {
                        Timber.i("absolutePath=${file.absolutePath}")
                        GlideApp.with(this@UserInfoActivity)
                                .load(file)
                                .centerCrop()
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .skipMemoryCache(true)
                                .placeholder(R.mipmap.icon_default_picture)
                                .into(icon_avatar)
                        mPresenter.updateUserInfo(file.absolutePath, nickname, userId)
                    }
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("UserInfoActivity").e("event.message=" + event.message)
        Timber.tag("UserInfoActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_MODIFY_LOGIN_PWD_TYPE -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.FINISH_ACTIVITY) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable!!.clear()
        EventBus.getDefault().unregister(this)
    }
}
